// 定义工艺bom树节点
interface TechTreeNode {
  id: string
  label: string
  level: number
  edit?: boolean
  path?: string
  bomId?: string
  // 第一层节点可以包含第二层节点
  children?: TechTreeNode[]
}

// 定义完整的树形结构
type TechniqueTree = TechTreeNode[]

/**
 * 将TechTreeNode树形结构转换为易读的字符串
 * @param nodes 节点数组
 * @param indentLevel 初始缩进层级（默认0）
 * @returns 格式化后的字符串
 */
export const formatTechTreeImpl = (nodes: TechTreeNode[]) => {
  // let index = 0
  function formatTechTree(nodes: TechTreeNode[], indentLevel = 0, parentId: string = 'root') {
    let treeStructure = ''
    // let tableStructure = ''
    // const indent = '\t'.repeat(indentLevel) // 生成对应层级的制表符缩进
    const indent = ''.repeat(indentLevel) // 取消制表符缩进

    nodes.forEach((node) => {
      // // 添加当前节点的label（带缩进）
      // result += `${indent}${node.label}\n`

      // 改成导出id
      treeStructure += `${indent}${node.id}/${node.label}/${parentId}/${node.path}\n`
      // index++

      //给表里填入内容
      // if (indentLevel == 2) {
      // tableStructure += `${node.id}/${node.label}/${node.path}\n`
      // }

      // 递归处理子节点（缩进层级+1）
      if (node.children && node.children.length > 0) {
        // const {treeStructure :treeS,tableStructure :tableS} = formatTechTree(node.children, indentLevel + 1, node.id)
        // treeStructure+=treeS;
        // tableStructure+=tableS

        // if (indentLevel == 1) {
        //   treeStructure += caculatePrtCount(node.children, indentLevel + 1)
        // } else {
        treeStructure += formatTechTree(node.children, indentLevel + 1, node.id)
        // }
      }
    })

    // return {treeStructure ,tableStructure}
    return treeStructure
  }

  const treeStructure = formatTechTree(nodes)
  // const openResult = treeStructure.treeStructure+treeStructure.tableStructure
  // const returnRes = index + '\n' + treeStructure
  // const returnRes = treeStructure
  return treeStructure
}

/**
 * 将TechTreeNode树形结构转换为易读的字符串
 * @param nodes 节点数组
 * @param indentLevel 初始缩进层级（默认0）
 * @returns 格式化后的字符串
 */
export const formatHandInTechniqueBomPrtCountImpl = (nodes: TechTreeNode[]) => {
  // let index = 0
  function formatTechTree(nodes: TechTreeNode[], indentLevel = 0, parentId: string = 'root') {
    let treeStructure = ''
    // let tableStructure = ''
    const indent = '\t'.repeat(indentLevel) // 生成对应层级的制表符缩进

    nodes.forEach((node) => {
      // 添加当前节点的label（带缩进）
      // result += `${indent}${node.label}\n`

      // 改成导出id
      treeStructure += `${indent}${node.label}\n`
      // index++

      //给表里填入内容
      // if (indentLevel == 2) {
      // tableStructure += `${node.id}/${node.label}/${node.path}\n`
      // }

      // 递归处理子节点（缩进层级+1）
      if (node.children && node.children.length > 0) {
        //   const { treeStructure: treeS, tableStructure: tableS } = formatTechTree(
        //     node.children,
        //     indentLevel + 1,
        //     node.id,
        //   )
        //   treeStructure += treeS
        //   // tableStructure+=tableS

        if (indentLevel == 1) {
          treeStructure += caculatePrtCount(node.children, indentLevel + 1)
        } else {
          treeStructure += formatTechTree(node.children, indentLevel + 1, node.id)
        }
      }
    })

    // return {treeStructure ,tableStructure}
    return treeStructure
  }

  function caculatePrtCount(nodes: TechTreeNode[], offset: number): string {
    const temp = new Map<string, number>()
    nodes.forEach((node) => {
      const oldCount = temp.get(node.label)
      if (oldCount === undefined) {
        temp.set(node.label, 1)
      } else {
        temp.set(node.label, oldCount + 1)
      }
    })
    let resString = ''
    const space = '\t'.repeat(offset)
    temp.forEach((value, key) => {
      resString += `${space}${key} ${value}\n`
    })
    return resString
  }

  const treeStructure = formatTechTree(nodes)
  // const openResult = treeStructure.treeStructure+treeStructure.tableStructure
  // const returnRes = index + '\n' + treeStructure
  // const returnRes = treeStructure
  return treeStructure
}

// 第三层节点创建器（私有方法，确保用户不能直接创建）
export class TreeManager {
  // 生成唯一ID
  private generateId(): string {
    return Date.now().toString(36) + Math.random().toString(36).slice(0, 5)
  }

  // 创建第一层节点
  createLevel1Node(label: string): TechTreeNode {
    return {
      id: this.generateId(),
      label,
      level: 1,
      edit: false,
      children: [],
    }
  }

  // 创建第二层节点
  createLevel2Node(): TechTreeNode {
    return {
      id: this.generateId(),
      label: '新建工步',
      edit: true,
      level: 2,
      children: [],
    }
  }

  // 内部方法，用于创建第三层节点（用户不能直接调用）
  createLevel3Node(label: string, bomId: string, path: string): TechTreeNode {
    return {
      id: this.generateId(),
      label,
      bomId,
      path,
      level: 3,
      children: [],
    }
  }

  // 向第二层节点添加第三层节点（通过此方法间接创建第三层节点）
  addLevel3Node(parent: TechTreeNode, node: TechTreeNode): void {
    console.log('level3Add')
    if (parent.level != 2) {
      return
    }
    parent.children?.push(node)
  }

  // 向第一层节点添加第二层节点
  addLevel2Node(parent: TechTreeNode, node: TechTreeNode): void {
    parent.children?.push(node)
  }

  // 向树形结构添加第一层节点
  addLevel1Node(tree: TechniqueTree, node: TechTreeNode): void {
    tree.push(node)
  }
}

export type { TechniqueTree, TechTreeNode }
